#!/usr/bin/perl

use POSIX;
use Data::Dumper;

my $fname = $ARGV[0] || 'enc.dat';

my %h = ();
my $h = 5;
my $min;
my $max;

while (<STDIN>) {

 next if $_ =~ /^#/;

 $_ =~ s/^\s*//;
 
 my @v = split /\s+/, $_;
 
 my $i = int   $v[0];
 my $v = 0.0 + $v[1];

 $h{$i} = $v;
}

my @k = sort{$a <=> $b}keys %h;

my ($min, $max) = @k[0,-1];

#
my $imin = ceil  $min;
my $imax = floor $max;

$imin = 1000 if $imin < 1000;
$imax = 7000 if $imax > 7000;

#
my %n = ();
for (my $i = $imin; $i <= $imax; $i += $h)
{
   if ( exists $h{$i} )
   {
      $n{$i} = $h{$i}
   }
   else
   {
      my $j0 = (grep{ $_ < $i }@k)[-1];
      my $j1 = (grep{ $_ > $i }@k)[0];
      
      my $v0 = $h{$j0};
      my $v1 = $h{$j1};
     
      $n{$i} = $v0 + ($v1-$v0) * ($i-$j0)/($j1-$j0);
   }
}

my $e = join ",", map{"($_,$n{$_})"}(sort{$a <=> $b}keys %n);

open CMD, "| runhaskell";

print CMD <<EOF;
{-# OPTIONS -XTypeOperators #-}

import Data.Binary
import FTable

main = do
  let f = fromList ($imin, $imax, $h) [$e] :: Int :->: Double
  encodeFile "$fname" f

EOF

close CMD;
